﻿using MQTTnet;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using Newtonsoft.Json;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace MqttClient
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var options = new MqttClientOptionsBuilder()
                        .WithClientId(Guid.NewGuid().ToString())
                         //.WithTcpServer("192.168.3.222", 1883)
                         .WithWebSocketServer("ws://localhost:44383/mqtt")
                        .WithCredentials("admin", "abc123!@#")
                        .WithCleanSession()
                        .Build();
            var mqttClient = new MqttFactory().CreateMqttClient();
            await mqttClient.ConnectAsync(options, CancellationToken.None);

            var random = new Random();
            while (true)
            {
                await Task.Delay(1000);
                await mqttClient.PublishAsync(
                new MqttApplicationMessage
                {
                    Topic = "test",
                    Payload = System.Text.ASCIIEncoding.UTF8.GetBytes(
                            JsonConvert.SerializeObject(new { Name = "current_temperature", Value = (random.NextDouble() * 100).ToString() })
                        )
                }
                , CancellationToken.None);
            }
            //await mqttClient.DisconnectAsync(new MqttClientDisconnectOptions
            //{
            //    ReasonCode = MqttClientDisconnectReason.NormalDisconnection
            //}, CancellationToken.None);

            //Console.ReadLine();
        }
    }
}
